<template>
  <el-dialog
    top="10vh"
    width="500px"
    title="添加/编辑"
    :visible.sync="dialogValue"
    :close-on-click-modal="false"
    append-to-body
  >
    <SubmitForm
      :rule-form="ruleForm"
      :rules="rules"
      :form-list="formList"
      @change="handleFormChange"
      @save="onSave"
      @close="dialogValue = false"
    />

  </el-dialog>
</template>

<script>
import { http } from '@/api'
export default {
  name: 'FormAdd',
  data() {
    return {
      apiKey: 'role',
      dialogValue: false,
      ruleForm: {
      },
      defaultForm: {
        name: '',
        code: '',
        sort: 0,
        remark: '',
        status: 1,
        menu_id: []
      },
      rules: {
        name: [{ required: true, message: '不能为空' }],
      },
      formList: [
        {
          label: '角色名称',
          prop: 'name',
          name: 'input',
          clearable: true,
          colSpan: 24
        },
        {
          prop: 'menu_id',
          label: '菜单',
          name: 'selectTree',
          checkStrictly: true,
          multiple: true,
          options: [],
          clearable: true,
          props: {
            children: 'children',
            label: 'name',
            value: 'id'
          },
          colSpan: 24
        },
        {
          label: '状态',
          prop: 'status',
          name: 'switch',
          colSpan: 12,
          activeValue: 1,
          inactiveValue: 0
        },
      ]
    }
  },
  methods: {
    handleFormChange({ key, val }) {

    },
    open(row) {
      this.dialogValue = true
      if (row) {
        http[this.apiKey].read(row.id).then(res => {
          this.ruleForm = {
            ...res.data,
            menu_id: res.data.menu_id.split(',').map(item => Number(item))
          }
          console.log('this.ruleForm',this.ruleForm)
        })
      } else {
        this.ruleForm = {
          ...this.defaultForm
        }
      }
      http.menu.list().then(res => {
        this.formList[1].options = res.data
      })
    },
    onSave() {
      http[this.apiKey][this.ruleForm.id ? 'update' : 'create'](this.ruleForm.id, {
        ...this.ruleForm,
        menu_id: this.ruleForm.menu_id.join(',')
      }).then(res => {
        this.$message.success('操作成功')
        this.dialogValue = false
        this.$emit('get-page')
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style>
